关于迷宫问题,常见会问能不能到达某点,以及打印到达的最短路径。可以用回溯法+递归来解决
代码一:dfs + 回溯
-
将矩阵外围以及路障统一设置为-1
-
设置current_step和next_step两个值。如果面临的点大于next_step,或者从未走过,就可以对它递归
-
存储矩阵:直接在原迷宫上修改,每个点标记的是从起点过来经过的步数,遇到0或者是比当前大至少2的,就考察
# -*- coding:utf-8 -*-
def init():
global graph
graph.append([-1, -1, -1, -1, -1, -1, -1])
graph.append([-1, 0, 0, -1, 0, 0, -1])
graph.append([-1, 0, -1, 0, 0, 0, -1])
graph.append([-1, 0, -1, 0, -1, -1, -1])
graph.append([-1, 0, -1, 0, 0, 0, -1])
graph.append([-1, 0, 0, 0, -1, 0, -1])
graph.append([-1, 0, 0, 0, 0, 0, -1])
graph.append([-1, -1, -1, -1, -1, -1, -1])
#深度优先遍历
def deepFirstSearch( steps , x, y ):
global graph
current_step = steps + 1
print(x, y, current_step )
graph[x][y] = current_step
next_step = current_step + 1
'''
遍历周围4个点:
如果周围节点不是-1 说明 不是障碍 在此基础上:
里面是0 说明没遍历过 我们把它修改成当前所在位置步数加1
里面比当前的next_step大 说明不是最优方案 就修改它
里面比当前next_step说明当前不是最优方案,不修改
'''
if not(x-1== 1 and y==1) and graph[x-1][y] != -1 and ( graph[x-1][y]>next_step or graph[x-1][y] ==0 ) : #上
deepFirstSearch(current_step, x-1 , y )
if not(x == 1 and y-1==1) and graph[x][y-1] != -1 and ( graph[x][y-1]>next_step or graph[x][y-1] ==0 ) : #左
deepFirstSearch(current_step, x , y-1 )
if not(x == 1 and y+1==1) and graph[x][y+1] != -1 and ( graph[x][y+1]>next_step or graph[x][y+1]==0 ) : #右
deepFirstSearch(current_step, x , y+1 )
if not(x+1== 1 and y==1) and graph[x+1][y] != -1 and ( graph[x+1][y]>next_step or graph[x+1][y]==0 ) : #下
deepFirstSearch(current_step, x+1 , y )
if __name__ == "__main__":
graph = []
init()
deepFirstSearch(-1,1,1)
print(graph[1][5])
代码二:也是回溯
这里0是可走,1是路障,用while来做循环。如果某点的附近有判断可走的新点,就将新点append进stack,走过了标记为-1;如果四个方向都没有,就从旧点从stack中pop掉,标上-1,进行回溯。
存储矩阵:stack中存储的0是可走,1是路障,-1是走过的或者是死路
maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,1,0,0,1],
[1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,1,0,1],
[1,1,0,0,0,0,0,1,0,1],
[1,1,1,1,1,1,1,1,1,1]
]
dirs = [lambda x, y: (x + 1, y),
lambda x, y: (x - 1, y),
lambda x, y: (x, y - 1),
lambda x, y: (x, y + 1)]
def mpath(x1, y1, x2, y2):
stack = []
stack.append((x1, y1))
while len(stack) > 0:
curNode = stack[-1]
if curNode[0] == x2 and curNode[1] == y2:
#到达终点
for p in stack:
print(p)
return True
for dir in dirs:
nextNode = dir(curNode[0], curNode[1])
if maze[nextNode[0]][nextNode[1]] == 0:
#找到了下一个
stack.append(nextNode)
maze[nextNode[0]][nextNode[1]] = -1 # 标记为已经走过,防止死循环
break
else:#四个方向都没找到
maze[curNode[0]][curNode[1]] = -1 # 死路一条,下次别走了
stack.pop() #回溯
print("没有路")
return False
mpath(1,1,8,8)